﻿#region

using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using CuongHanh.Context;
using CuongHanh.DAL;
using CuongHanh.Models;
using Ext.Net.MVC;

#endregion

namespace CuongHanh.Controllers.BO
{
    public class AccountController : ABaseController
    {
        private readonly UnitOfWork _unitOfWork = new UnitOfWork();

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            if(CheckAllSession())
                return RedirectToAction("Index",
                        "Home");
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(User model,
                string returnUrl)
        {
            if(ModelState.IsValid)
            {
                User cUser = _unitOfWork.FirstOrDefault<User>(c => c.Username == model.Username && !c.Inactive);
                if(cUser != null
                   && cUser.Password == model.Password.GetMd5())
                {
                    SetAllSession(cUser);
                    FormsAuthentication.SetAuthCookie(cUser.Username, false);
                    return new FormPanelResult
                           {
                                   Script = string.Format("location.href='{0}';",
                                           Url.Action("Index",
                                                   "AHome"))
                           };
                }
                return new FormPanelResult
                       {
                               Script = "App.Username.markInvalid('Invalid username or password!');App.Password.markInvalid('Invalid username or password!');"
                       };
            }
            return View(model);
        }

        #region Session function

        private void SetAllSession(User user)
        {
            Session[AppUtil.USER_ID] = user.Id;
            Session[AppUtil.USERNAME] = user.Username;
        }

        private bool CheckAllSession()
        {
            if(Session[AppUtil.USER_ID] != null
               &&
               Session[AppUtil.USERNAME] != null)
                return true;
            return false;
        }

        #endregion

        public ActionResult LogOff()
        {
            Session.Clear();
            FormsAuthentication.SignOut();

            HttpCookie httpCookie = Response.Cookies[FormsAuthentication.FormsCookieName];
            if (httpCookie != null)
            {
                httpCookie.Expires = DateTime.Now.AddYears(-1);
            }
            string userName = (User != null)
                                      ? User.Identity.Name
                                      : "";
            return RedirectToAction("Index",
                                    "Home");
        }
    }
}
